import {
  wxml,
  style
} from './demo'

import {
  getImage
} from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    show: false,
    images: [],
    isGenerate: [],
    poster: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      poster: options.url
    })
    this.widget = this.selectComponent('.widget')
    setTimeout(() => {
      this.getImage()
    }, 1000);
    
  },
  getImageInfo(index) {
    if (this.data.isGenerate.indexOf(index) !== -1) {
      return false
    }
    wx.showLoading({
      title: '生成中...',
      mask: false
    })
      wx.getImageInfo({
      src: this.data.images[index],
      success: res => {
        this.renderToCanvas(index, res.width, res.height)
      }
    })
  },
  renderToCanvas(index, width, height) {
    const p1 = this.widget.renderToCanvas({
      wxml: wxml(this.data.images[index], this.data.poster),
      style: JSON.parse(style(height, width))
    })
    p1.then((res) => {
      this.container = res
      this.extraImage(index)
    })
  },
  extraImage(index) {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      this.data.images.splice(index, 1, res.tempFilePath)
      this.setData({
        images: this.data.images,
        isGenerate: this.data.isGenerate.concat(index)
      })
    })
    wx.hideLoading({
      success: (res) => {
        this.setData({
          show: true
        })
      }
    })
  },
  change(e) {
    this.getImageInfo(e.detail.current)
  },
  getImage() {
    return new Promise((resolve, reject) => {
      getImage({
        type: 1
      }).then(res => {
        if(res.data && res.data.length > 0){
          this.setData({
            images: res.data
          })
          this.getImageInfo(0)
        } else {
         wx.showToast({
           title: '无海报模板',
           icon: 'error'
         })
        }
      })
    })
  }
})